<?php	
	require_once KLEO_LIB_DIR.'core.lib.php';

	class users extends usersmodel{
	
		var $registered = 0;
		/* Call to the model Class */
		function __construct(){
			$this->index();
		}

		function load_users(&$buff){
			switch($_GET['action']){
				case 'register':
					$this->show_register($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=register">'.L_REGISTER.'</a>';
				break;
				case 'uid':
					$this->show_user_profile($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=uid&uid='.$_GET['uid'].'">'.$this->get_username($_GET['uid']).'</a>';
				break;
				case 'login':
					$this->show_login($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=login">Login</a>';
				break;
				case 'activate':
					$this->show_activate($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=activate">Activate user</a>';
				case 'logout':
					$this->show_logout($ubuff);
				break;
				case 'bios':
					$this->show_bios($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&show_bios">Bios</a>';
				break;
				case 'stats':
					$this->show_statistics($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=stats">Statistics</a>';
				break;
				case 'profile':
					if(isset($_POST['do_profile'])){
						$this->do_profile();
					}
					$this->show_profile($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=profile">Profile</a>';
				break;
				case 'avatar':
					$this->show_avatar($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=avatar">Avatar</a>';
				break;
				case 'recovery':
					$this->show_recovery($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a> » <a href="?module=users&action=recovery">Recover password</a>';
				break;
				case 'dologin':
					$this->do_login($ubuff);
				break;
				case 'doreg':
					$this->do_register($ubuff);
				break;
				case 'doactivation':
					$this->do_activate($ubuff);
				break;
				case 'dobios':
					$this->do_bios($ubuff);
				break;
				default:
					$this->show_login($ubuff);
					$this->data['breadcrumb'] = '<a href="index.php" title="home">Home</a> » <a href="?module=users">Users</a>';
				break;
			}


			$this->compile($ubuff, $ubuff);
			$this->tpl_set("BREADCRUMB", $this->data['breadcrumb'], $bbuff, $buff);
			$this->tpl_set("WEB_CONTENT", $ubuff, $bbuff, $buff);
		}

		function show_user_profile(&$buff){
			$uid = (int)$_GET['uid'];
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users, ".KLEO_TABLE_PREFIX."users_profiles WHERE ".KLEO_TABLE_PREFIX."users_profiles.uid = ".KLEO_TABLE_PREFIX."users.uid AND ".KLEO_TABLE_PREFIX."users.uid = $uid LIMIT 1");
			while($row = $this->fetch_array($query)){

				if($row['job'] !== false && $row['town'] !== false){
					$row['job'] = $row['town'].' | ';
				}
				if($row['sex'] == 1){
					$row['sex'] = L_MALE;
				} else {
					$row['sex'] = L_FEMALE;
				}
				if(isset($row['lastfm'])){
					$listening = L_LISTENING_TO.': '.$this->get_last_track($row['lastfm']);
				} else {
					$listening = false;
				}
				if(!empty($row['twitter'])){
					$twitter_status = $this->get_last_twit($row['twitter']);
				} else {
					$twitter_status = '<small>'.L_NO_TWITTER_YET.'</small>';
				}
				if(strlen($row['bios'])>150){
					$bio = substr($row['bios'],0,150).'... <a href="#full_bio" onclick="extend_bio();">['.L_READ_MORE.']</a>';
				} else {
					$bio = $row['bios'];
				}

				$this->tpl_load('public.tpl', $buff);
				$this->get_group($row['uid'],$gid);
				$this->get_group_name($gid,$group);
				$this->tpl_set(array(
					"AGE" => $this->calculate_age($row['age']),
					"BIO" => $bio,
					"FULL_BIO" => $row['bios'],
					"JOB" => $row['job'],
					"MOVIES" => $row['movies'],
					"MUSIC" => $row['music'],
					"SPORTS" => $row['sports'],
					"BOOKS" => $row['books'],
					"LISTENING" => $listening,
					"NAME" => $row['nicename'],
					"SEX" => $row['sex'],
					"TOWN" => $row['town'],
					"TWITTER_STATUS" => $twitter_status->text,
					"USERNAME" => $row['username'],
					"USER_GROUP" => $group,
					"AVATAR_URL" => $this->get_username_avatar($row['uid']),
					"SOCIAL_BOOKMARKS" => $this->get_social_bookmarks($row['uid'])
				), false, $buff, $buff);
			}
		}

		function show_register(&$buff){
			if(!$this->is_logged()){
				$this->tpl_load('register.tpl', $buff);
			} else {
				$this->show_login($buff);
			}
		}

		function show_recovery(&$buff){
			if(!$this->is_logged()){
				$this->tpl_load('recover.tpl', $buff);
			} else {
				$this->show_login($buff);
			}
		}

		function show_login(&$ubuff){
			if(!$this->is_logged()){
				$this->tpl_load('login.tpl', $ubuff);
			} else {
				$this->tpl_load('pannel.tpl', $ubuff);
				$this->get_group($_SESSION['uid'],$gid);
				$this->get_group_name($gid,$group);
				if(strtolower($group) !== 'admin' && strtolower($group) !== 'chuck'){
 					$alink = NULL;
				} else {
					$alink = '<a href="?module=admin">'.L_ADMIN_PANNEL.'</a>';
				}
				$avatar = $this->get_username_avatar($_SESSION['uid']);
				if(empty($avatar)){
					$info = $this->get_user_info($this->get_username($_SESSION['uid']));
					if(!$this->get_gravatar($info['email'])){
						$avatar = 'media/avatars/default.png';
					} else {
						$avatar = $this->get_gravatar($info['email']);
					}
				}
				$this->tpl_set(array(
						"USERNAME" => $this->get_username($_SESSION['uid']),
						"GROUP" => $group,
						"ADMIN_PANNEL_LINK" => $alink,
						"AVATAR_URL" => $avatar
						),
				false,$ubuff,$ubuff);
			}
		}

		function show_activate(&$abuff){
			$this->tpl_load('activate.tpl', $abuff);
		}

		function show_logout(){
			unset($_SESSION['user']);
			unset($_SESSION['uid']);
			unset($_SESSION['group']);
			$this->appredirect("index.php?module=users");
		}
		
		function show_bios(&$bibuff){
			if($this->is_logged()){
				$uid = $_SESSION['uid'];
				$this->tpl_load('bios.tpl', $bibuff);
				$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_profiles WHERE uid = $uid LIMIT 1");
				if($this->num_rows($query) !== 0){
					while($row = $this->fetch_array($query)){
						$bios = $row['bios'];
					}
				} else {
					$bios = NULL;
				}

				$this->tpl_set("USER_BIOS", $bios, $bibuff, $bibuff);
			}
		}

		function show_statistics(&$sbuff){

			if($this->is_logged()){
				$uid = $_SESSION['uid'];

				$this->tpl_load('statistics.tpl', $sbuff);

				$comments_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."comments WHERE coaid = $uid");
				$num_comments = $this->num_rows($comments_query);

				$total_comments_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."comments");
				$total_num_comments = $this->num_rows($total_comments_query);

				$comments_percent = $total_num_comments/100*$num_comments;

				$users_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE uid = $uid LIMIT 1");
				while($row = $this->fetch_array($users_query)){
					$since = $row['rdate'];
				}
				$this->get_group_name($uid, $group_name);

				$total_percent = 100-$total_num_comments;


				/*
				 * Load the Google Chart API and make the comments chart...
				 */
				$this->apploadlib(KLEO_SOURCE_DIR."lib/third_party/gchart/charts.lib.php", "gPieChart", $pie);
				$pie->dataColors = array("CCCCCC", "000000");
				$pie->values = Array($total_num_comments,$num_comments);
				$pie->valueLabels = Array("Rest - {$total_percent}%", "Yours - {$total_num_comments}%");
				$pie->set3D(true);
				$pie->setTitle(L_TOTAL_COMMENTS);
				$pie->addBackground('#333333','#000000');
				$pieurl = $pie->getUrl();


				/*
				 * Set the template values
				 */
				$this->tpl_set("TOTAL_COMMENTS", $num_comments, $sbuff, $sbuff);
				$this->tpl_set("MEMBER_GROUP", $group_name, $sbuff, $sbuff);
				$this->tpl_set("REGISTRATION_DATE", $since, $sbuff, $sbuff);
				$this->tpl_set("COMMENTS_PIE_URL", $pieurl, $sbuff, $sbuff);


			}			
		}

		function show_profile(&$pbuff){

			if(isset($_POST['do_profile'])){
				$this->do_profile();
			}
			$uid = $_SESSION['uid'];
			$this->tpl_load('profile.tpl', $pbuff);
			$this->apploadlib(KLEO_LIB_DIR.'forms.lib.php','kleoforms',$form);
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_profiles WHERE uid = '$uid' LIMIT 1");
			$row = $this->fetch_array($query);
			$country_select = $form->Get_Countries_Select($row['country'],'form-comment');
			$this->tpl_set(array(
				"MSN" => $row['msn'], 
				"YAHOO" => $row['yahoo'],
				"GMAIL" => $row['gmail'],
				"WEB" => $row['web'],
				"JOB" => $row['job'],
				"AGE" => $row['age'],
				"TOWN" => $row['town'],
				"COUNTRY" => $row['country'],
				"MUSIC" => $row['music'],
				"MOVIES" => $row['movies'],
				"BOOKS" => $row['books'],
				"SPORTS" => $row['sports'],
				"DELICIOUS" => $row['delicious'],
				"TWITTER" => $row['twitter'],
				"FLICKR" => $row['flickr'],
				"LASTFM" => $row['lastfm'],
				"DIGG" => $row['digg'],
				"COUNTRY_SELECT" => $country_select
			), false, $pbuff, $pbuff);

		}

		function show_avatar(&$abuff){
			$uid = $_SESSION['uid'];
			$this->tpl_load('avatar.tpl', $abuff);

			if(isset($_POST['do_avatar'])){
				$this->do_avatar();
			}
	
		}

		function do_login(){
			$username = $_POST['username'];
			$password = $_POST['password'];
			$this->kleo_login($username, $password);
			//Referer session
			if(empty($_SESSION['referer'])){
				$_SESSION['referer'] = $_SERVER['HTTP_REFERER'];
			}
			$this->appredirect($_SESSION['referer']);
			unset($_SESSION['referer']);
		}

		function do_register(&$message){
			$username = $_POST['username'];
			$password = $_POST['password'];
			$email = $_POST['email'];
 			if($this->is_email($email) && !empty($username) && !empty($password) && !$this->is_registered_user($username,$email)){
				$message = L_REGISTRATION_COMPLETE;
				$this->add_user($username,$password,$email);
			} else {
				$message = L_REGISTRATION_ERROR;
			}
		}

		function do_bios(){
			$bios = $_POST['bios'];
			$uid = $_SESSION['uid'];
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_profiles WHERE uid = $uid LIMIT 1");
			if($this->num_rows($query)>0){
				$this->query("UPDATE ".KLEO_TABLE_PREFIX."users_profiles SET bios = '$bios' WHERE uid = $uid LIMIT 1 ;");

			} else {
				$this->query("INSERT INTO ".KLEO_TABLE_PREFIX."users_profiles (bios, uid) VALUES ('$bios','$uid')");
			}
			$this->appredirect("index.php?module=users&action=bios");
		}

		function do_activate(){
			$hash = $_POST['hash'];
			$username = $_POST['username'];
			if(strlen($hash) !== 32 or !$this->is_user($username)){
				$this->apperror("Hack attempt!");
			}
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE MD5(salt) = '$hash' AND username = '$username' AND status = 0 LIMIT 1");
			$row = $this->fetch_array($query);
			(int)$id = $row['uid'];
			if($this->activate_user($id,$hash,$username)){
				$this->activate_user($id,$hash,$username);
				$this->apperror(L_USER_ACTIVATED_SUCCESSFULLY);
			} else {
				$this->apperror(L_USER_ACTIVATED_ERROR);
			}
		}


		function do_profile(){
				$uid = $_SESSION['uid'];
				$msn = $_POST['msn'];
				$yahoo = $_POST['yahoo'];
				$gmail = $_POST['gmail'];
				$web = $_POST['web'];
				$job = $_POST['job'];
				$age = $_POST['age'];
				$country = $_POST['country'];
				$town = $_POST['town'];
				$music = $_POST['music'];
				$movies = $_POST['movies'];
				$books = $_POST['books'];
				$sports = $_POST['sports'];
				$twitter = $_POST['twitter'];
				$delicious = $_POST['delicious'];
				$digg = $_POST['digg'];
				$flickr = $_POST['flickr'];
				$lastfm = $_POST['lastfm'];
		
				$rows_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_profiles WHERE uid = '$uid'");
				$rows = $this->num_rows($rows_query);

				if($rows > 0){
					$this->query("UPDATE ".KLEO_TABLE_PREFIX."users_profiles SET msn = '$msn', yahoo = '$yahoo', gmail = '$gmail', web = '$web', job = '$job', age = '$age', country = '$country', music = '$music', movies = '$movies', town = '$town', books = '$books', sports = '$sports', delicious = '$delicious', twitter = '$twitter', digg = '$digg', flickr = '$flickr', lastfm = '$lastfm' WHERE uid = $uid LIMIT 1;");
				} else {
					$this->query("INSERT INTO ".KLEO_TABLE_PREFIX."users_profiles (uid, msn, yahoo, gmail, web, job, age, country, town, music, movies, books, sports, twitter, delicious, digg, flickr, lastfm) VALUES ('$uid','$msn','$yahoo','$gmail','$web','$job','$age','$country','$town','$music','$movies','$books','$sports', '$twitter', '$delicious', '$digg', '$flickr', '$lastf')");
				}
		}

		function do_avatar(){
			
			if(!is_dir(KLEO_MEDIA_DIR.'avatars/'.$this->get_username($_SESSION['uid']))){
				mkdir(KLEO_MEDIA_DIR.'avatars/'.$this->get_username($_SESSION['uid']));
			}
			$target = KLEO_MEDIA_DIR.'avatars/'.$this->get_username($_SESSION['uid']).'/'.basename($_FILES['avatar']['name']);

			move_uploaded_file($_FILES['avatar']['tmp_name'], $target);
			chmod($target, 0755);
			/*
			 * Security fix
			 * http://www.exploit-db.com/exploits/17005/
			 */
			if(!getimagesize($target)){
				unlink($target);
				$this->appredirect('index.php');
			}

	 		$uid = $_SESSION['uid'];
			$useravatar = $this->get_username($_SESSION['uid']).'/'.$_FILES['avatar']['name'];
	 		$ouseravatar = $this->get_username($_SESSION['uid']).'/thumb-'.$_FILES['avatar']['name'];

			if($this->user_has_profile($uid)){
				$this->query("UPDATE `".KLEO_TABLE_PREFIX."users_profiles` SET `avatar` = '$ouseravatar' WHERE `profileid` = $uid LIMIT 1 ;");
			} else {
				$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."users_profiles` (
					`profileid` ,
					`uid` ,
					`nicename` ,
					`msn` ,
					`yahoo` ,
					`gmail` ,
					`web` ,
					`music` ,
					`movies` ,
					`sports` ,
					`bios` ,
					`age` ,
					`job` ,
					`country` ,
					`avatar` ,
					`delicious` ,
					`twitter` ,
					`digg` ,
					`flickr` ,
					`lastfm` ,
					`facebook`
					) VALUES (
					NULL , '$uid', '', '', '', '', '', '', '', '', '', '', '', '', '$ouseravatar', '', '', '', '', '', ''
					);
				");
			}

			require_once KLEO_LIB_DIR.'gd.lib.php';
			$gd = new kleogd();
			$gd->thumblr_static(KLEO_MEDIA_DIR.'avatars/'.$useravatar,64,64,KLEO_MEDIA_DIR.'avatars/'.$ouseravatar);
			$gd->thumblr_static(KLEO_MEDIA_DIR.'avatars/'.$useravatar,24,24,KLEO_MEDIA_DIR.'avatars/tiny-'.$ouseravatar);

			//Reset the _POST values
			$this->appreload();
		}

	}
?> 
